package com.heima.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.constant.ItemConstant;
import com.heima.dto.DeductStockDTO;
import com.heima.entity.Item;
import com.heima.item.mapper.ItemMapper;
import com.heima.item.service.IItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.po.ItemDoc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author zhuan
 * @since 2023-09-06
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Transactional
    @Override
    public void deductStock(List<DeductStockDTO> dtos) {
        if(dtos == null || dtos.size() == 0){
            return;
        }
        for (DeductStockDTO dto : dtos) {
            Item item = itemMapper.selectById(dto.getId());
            Integer stock = item.getStock();
            stock = stock - dto.getNum();
            item.setStock(stock);
            itemMapper.updateById(item);
        }
    }

    public Boolean saveItem(Item item){
        int i = itemMapper.insert(item);
        if(i > 0 ){
            redisTemplate.opsForSet().add("home_page_hot_goods", JSON.toJSONString(item));
        }
        return i == 1 ? true : false;
    }

    @Override
    public List<ItemDoc> page(int page, int size) {
        Page<Item> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getStatus, ItemConstant.ITEM_STATUS_NORMAL);
        Page<Item> itemPage = itemMapper.selectPage(pageParam, queryWrapper);
        //item集合转换为itemDoc集合
        List<ItemDoc> itemDocList = itemPage.getRecords().stream().map(item -> {
            ItemDoc itemDoc = new ItemDoc(item);
            return itemDoc;
        }).collect(Collectors.toList());
        return itemDocList;
    }
}
